package com.gensdai.leliang;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.gensdai.leliang.activity.user_enter;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.common.bean.UpdateInfoBean;
import com.gensdai.leliang.common.clickinterface.MenuItemChangeListener;
import com.gensdai.leliang.fragment.FragmentCartCard;
import com.gensdai.leliang.fragment.FragmentMyCard;
import com.gensdai.leliang.fragment.FragmentRecyclerHome;
import com.gensdai.leliang.fragment.FragmentTypeCard;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.retrofitUtils.BaseObserver;
import com.gensdai.leliang.retrofitUtils.ModelFilteredFactory;
import com.gensdai.leliang.serve.ActionEnter;
import com.gensdai.leliang.utils.Download;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.FragmentEvent;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.gensdai.leliang.R.id.geshu;

public class MainBottomNavigation extends BaseActivityNoAbs implements MenuItemChangeListener {


    @BindView(R.id.bottom_navigation_bar)
    BottomNavigationBar bottomNavigationBar;
    @BindView(R.id.replaceFrame)
    FrameLayout replaceFrame;

    List<Fragment> fragms;

    SharedPreferences share;
    SharedPreferences.Editor ed;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_bottom_navigation);
        ButterKnife.bind(this);

        share = getSharedPreferences("User", MODE_PRIVATE);
        ed = share.edit();
        initFragment(); //初始化fragment
        initLable();       //初始化lable
        startMyservice();
        checkVersion();
    }

    /**
     * 启动自动登录
     */
    private void startMyservice() {
        Intent start = new Intent(this, ActionEnter.class);
        this.startService(start);
    }

    private void initFragment() {
        fragms = new ArrayList<>();

//        fragms.add(FragmentShopCard.NewInstance("home"));
        fragms.add(new FragmentRecyclerHome());
        fragms.add(FragmentTypeCard.NewInstance());
//        fragms.add(new CartListFragment());
        fragms.add(FragmentCartCard.NewInstance(-1));
        fragms.add(FragmentMyCard.NewInstance());


    }


    private void initLable() {
        bottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
        //颜色设置必须在init lable之前设置
        bottomNavigationBar
                .setActiveColor(R.color.baseColor)
                .setInActiveColor(R.color.icon_lable_unselect_color)
                .setBarBackgroundColor(R.color.bgColor_new);
        bottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);
        bottomNavigationBar.addItem(new BottomNavigationItem(R.mipmap.home_normal, "商城"));
        bottomNavigationBar.addItem(new BottomNavigationItem(R.mipmap.type_normal, "分类"));
        bottomNavigationBar.addItem(new BottomNavigationItem(R.mipmap.cart_normal, "购物车"));
        bottomNavigationBar.addItem(new BottomNavigationItem(R.mipmap.my_normal, "我的"));
        bottomNavigationBar.setFirstSelectedPosition(0)
                .initialise();


        //切换选项卡监听
        bottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                Log.d("onTabSelected", "onTabSelected" + position);
                if (position == 3 || position == 2) {
                    if (!getSharedPreferences("User", MODE_PRIVATE).getBoolean("enter_state", false)) {
                        Intent user_go_enter = new Intent(MainBottomNavigation.this, user_enter.class);
                        startActivity(user_go_enter);


                        //
                        if (currentPosition != 3 && currentPosition != 2) {

                            bottomNavigationBar.selectTab(currentPosition);
                        } else {
                            if (currentPosition != 0)
                                bottomNavigationBar.selectTab(0);
                        }

                        return;
                    }
                }
                lableClick(position);
            }

            @Override
            public void onTabUnselected(int position) {
                Log.d("onTabUnselected", "position" + position);
            }

            @Override
            public void onTabReselected(int position) {
                Log.d("onTabReselected", "position" + position);

            }
        });

        bottomNavigationBar.selectTab(0);
    }


    private void lableClick(int position) {
        switchContent(position);
    }

    private int currentPosition = 0;

    private Fragment currentFragment;
    FragmentManager fmManager = getSupportFragmentManager();

    private void switchContent(int position) {
        currentPosition = position;
        Fragment fragment = fragms.get(position);
        FragmentTransaction fmTrans = fmManager.beginTransaction();
        if (currentFragment != null) {
            if (currentFragment == fragment) {
                return;
            } else {

                if (!fragment.isAdded()) {
                    fmTrans.hide(currentFragment).add(R.id.replaceFrame, fragment).commit();
                } else {
                    fmTrans.hide(currentFragment).show(fragment).commit();
                }

                //某一个fragment需要做实时更新 ，直接再设置当前fragment之前销毁原来的fragment
                if (currentFragment instanceof FragmentCartCard) {
                    fmTrans.remove(currentFragment);
                }

                currentFragment = fragment;
            }
        } else {
            fmTrans.add(R.id.replaceFrame, fragment).commit();
            currentFragment = fragment;
        }
    }


    //该接口实现主要是fragmet 商城 与 fragment 分类的交互
    @Override
    public void changePosition(int id) {
        currentPosition = 1;
        Fragment fragment = fragms.get(1);
        FragmentTransaction fmTrans = fmManager.beginTransaction();

        if (currentFragment != null) {
            if (currentFragment == fragment) {
                return;
            } else {
                if (!fragment.isAdded()) {
                    //判断是否创建过 没创建过就用bundle传递数据过去
                    Bundle args = new Bundle();
                    args.putInt(FragmentTypeCard.EXTRA_TYPE_POSITION, id);
                    fragment.setArguments(args);
                    fmTrans.hide(currentFragment).add(R.id.replaceFrame, fragment).commit();
                } else {
                    //已经是创建过的状态 直接调用方法 更新view
                    ((FragmentTypeCard) fragment).updateview(id);
                    fmTrans.hide(currentFragment).show(fragment).commit();
                }
                currentFragment = fragment;
            }
        } else {
            fmTrans.add(R.id.replaceFrame, fragment).commit();
            currentFragment = fragment;
        }

        bottomNavigationBar.selectTab(1);
    }

    private String url = "";// APK下载路径

    /*检测自动更新*/
    private void checkVersion() {

        Map<String, String> params = new HashMap<>();
        params.put("phoneType", "android");
        params.put("version", AppApplication.mVersionName);
//        params.put("phoneType", "ios");
        Observable ob = ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().UpdateRequestParse(params));

        BaseObserver bo = new BaseObserver<UpdateInfoBean>(this) {
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
                Log.d("checkVersion", "onSubscribe");
                super.onSubscribe(d);
            }

            @Override
            public void onHandleSuccess(final UpdateInfoBean updateInfoBean) {
                Log.d("checkVersion", "请求服务器成功 " + AppApplication.mVersionCode + "  :" + AppApplication.mVersionName);
                if (updateInfoBean == null) {
                    return;
                }
                if (updateInfoBean.url == null) {
                    return;
                }
                if (updateInfoBean.version == null) {
                    return;
                }
                url = updateInfoBean.url;
                if (TextUtils.equals(updateInfoBean.version, AppApplication.mVersionName)) {
                    //版本相同需要则不需要提示
                } else {
                    //如果不相同就显示dialog   //还要根据versionCode 来判断版本的高低
//                    dialog = UpdateDialog.newInstance(updateInfoBean.content,updateInfoBean.forceUpdate);
//                    dialog.show(getFragmentManager()/*getFragmentManager()*/, "UpdateDialog");

                    final AlertDialog.Builder normalDialog =
                            new AlertDialog.Builder(MainBottomNavigation.this);


                    View view = getLayoutInflater().inflate(R.layout.dialog_update_fragment, null);
                    TextView label = ((TextView) view.findViewById(R.id.updateTitle));
                    TextView labelMessage = ((TextView) view.findViewById(R.id.message));
                    TextView cancel_btn = ((Button) view.findViewById(R.id.cancel_btn));
                    TextView update_btn = ((Button) view.findViewById(R.id.update_btn));
                    labelMessage.setText(updateInfoBean.content);
                    label.setMovementMethod(LinkMovementMethod.getInstance());
                    normalDialog.setCancelable(false);

                    normalDialog.setView(view);
                    // 显示
                    alertDialog = normalDialog.create();
                    alertDialog.show();

                    cancel_btn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            alertDialog.dismiss();
                            if (1 == updateInfoBean.forceUpdate) {
                                System.exit(0);
                            }
                        }
                    });
                    update_btn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            openApplicationMarket();
                            if (1 == updateInfoBean.forceUpdate) {

                            } else {
                                alertDialog.dismiss();
                            }
//                System.exit(0);
                        }
                    });
                }

            }

            @Override
            public void onHandleError(int code, String message) {
                Log.d("checkVersion", "请求服务器成功,但是返回了错误 " + code + " :" + message);
            }
        };

        ob.doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(@NonNull Disposable disposable) throws Exception {

                Log.d("checkVersion", "accept");
            }
        }).subscribe(bo);

    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    private long firstTime = 0;


    public AlertDialog alertDialog;

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
//        Intent  it =  new Intent(this,LogisticsInfoActivity.class);
//        it.putExtra("orderid","f5863714f76d470fa70df7110121e9e0");
//                    startActivity(it);
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {                                         //如果两次按键时间间隔大于2秒，则不退出
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;//更新firstTime
                    return true;
                } else {
                    getSharedPreferences("User", MODE_PRIVATE).edit().putBoolean("enter_state", false).commit();//两次按键小于2秒时，退出应用
                    System.exit(0);
                }
                break;

        }
        return super.onKeyUp(keyCode, event);
    }

    /**
     * 通过包名 在应用商店打开应用
     */
    private void openApplicationMarket() {
        try {
            if (!url.equals("")) {
                Download download = new Download();
//            download.StartDownload("http://" + url, "乐粮乐成长", this, true);
                download.StartDownload(url, "乐粮乐成长", this, true);
            } else {
                String str = "market://details?id=" + "com.gensdai.leliang";
                Intent localIntent = new Intent(Intent.ACTION_VIEW);
                localIntent.setData(Uri.parse(str));
                startActivity(localIntent);
            }

        } catch (Exception e) {
            // 打开应用商店失败 可能是没有手机没有安装应用市场
            e.printStackTrace();
            Toast.makeText(AppApplication.getContext(), "打开应用商店失败",
                    Toast.LENGTH_SHORT).show();
            // 调用系统浏览器进入商城
            String url = "https://www.lelong1788.com/";
            openLinkBySystem(url);
        }
    }


    /**
     * 调用系统浏览器打开网页
     *
     * @param url 地址
     */
    private void openLinkBySystem(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }

}